package br.com.wagnerpaz.battlemaniacs.model;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class XMLStorer
{
	public void storeFighter(Fighter f)
	{
		
	}
	
	public static Fighter retrieveFighter(InputStream in)
	{
		Fighter fighter = new Fighter();
		Status  status  = new Status();
		Map<Attribute, AttributeValue> attributes = new HashMap<Attribute, AttributeValue>();
		
		fighter.setStatus(status);
		status.setAttributes(attributes);
		
		try
		{
			Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
			
			//FIGHTER
			Node fighterNode = d.getElementsByTagName("fighter").item(0);
			fighter.setName( fighterNode.getAttributes().getNamedItem("name").getTextContent() );
			
			//ATTRIBUTE-SET
			Node attributeSetNode = d.getElementsByTagName("attribute-set").item(0);
			
			NodeList statusChildren = attributeSetNode.getChildNodes();
			for(int i = 0; i < statusChildren.getLength(); i++)
			{
				Node att = statusChildren.item(i);
				int type = att.getNodeType();
				
				if(type == Node.ELEMENT_NODE)
				{
					String name  = att.getAttributes().getNamedItem("name") .getTextContent();
					String max   = att.getAttributes().getNamedItem("max")  .getTextContent();
					String value = att.getAttributes().getNamedItem("value").getTextContent();
					
					Attribute namedAtt   = Attribute.getByName(name);
					Integer   maxInt   = Integer.parseInt(max);
					Integer   valueInt = Integer.parseInt(value);
					
					attributes.put( namedAtt, new AttributeValue(maxInt, valueInt) );
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return fighter;
	}
}
